<?php
declare (strict_types = 1);

namespace app\admin\service;

use think\facade\Filesystem;
use think\facade\Db;

/**
 * 文件清理服务类
 */
class FileCleanupService
{
    /**
     * 清理重复的头像文件
     * 保留最新的，删除旧的
     */
    public static function cleanupDuplicateAvatars(): array
    {
        try {
            $disk = Filesystem::disk('public');
            $result = [
                'cleaned' => 0,
                'errors' => 0,
                'details' => []
            ];

            // 获取所有用户的头像信息
            $users = Db::table('admin')
                ->field('id,username,avatar')
                ->where('avatar', '<>', '')
                ->where('avatar', 'not null')
                ->select();

            foreach ($users as $user) {
                if (strpos($user['avatar'], '/storage/') === false) {
                    continue;
                }

                $avatarPath = str_replace('/storage/', '', $user['avatar']);
                $pathInfo = pathinfo($avatarPath);
                $directory = $pathInfo['dirname'];

                // 检查同一目录下是否有其他相似的文件
                if ($disk->exists($directory)) {
                    $files = $disk->files($directory);
                    $userFiles = [];

                    foreach ($files as $file) {
                        // 排除缩略图
                        if (strpos(basename($file), 'thumb_') !== 0) {
                            $userFiles[] = $file;
                        }
                    }

                    // 如果有多个文件，保留最新的
                    if (count($userFiles) > 1) {
                        // 按修改时间排序
                        usort($userFiles, function($a, $b) use ($disk) {
                            return $disk->lastModified($b) - $disk->lastModified($a);
                        });

                        // 保留第一个（最新的），删除其他的
                        $kept = array_shift($userFiles);
                        foreach ($userFiles as $oldFile) {
                            try {
                                UploadService::deleteFile($oldFile);
                                $result['cleaned']++;
                                $result['details'][] = "删除重复文件: {$oldFile}";
                            } catch (\Exception $e) {
                                $result['errors']++;
                                $result['details'][] = "删除失败 {$oldFile}: " . $e->getMessage();
                            }
                        }
                    }
                }
            }

            return [
                'code' => 0,
                'msg' => '清理完成',
                'data' => $result
            ];

        } catch (\Exception $e) {
            return [
                'code' => 1,
                'msg' => '清理失败：' . $e->getMessage(),
                'data' => null
            ];
        }
    }

    /**
     * 清理孤立的文件（数据库中没有引用的文件）
     */
    public static function cleanupOrphanedFiles(): array
    {
        try {
            $disk = Filesystem::disk('public');
            $result = [
                'cleaned' => 0,
                'errors' => 0,
                'details' => []
            ];

            // 获取所有数据库中引用的头像文件
            $usedAvatars = Db::table('admin')
                ->field('avatar')
                ->where('avatar', 'like', '/storage/%')
                ->column('avatar');

            $usedPaths = array_map(function($avatar) {
                return str_replace('/storage/', '', $avatar);
            }, $usedAvatars);

            // 检查avatars目录下的所有文件
            $avatarDir = 'avatars';
            if ($disk->exists($avatarDir)) {
                $allFiles = $disk->allFiles($avatarDir);
                
                foreach ($allFiles as $file) {
                    // 跳过缩略图，它们会在主文件删除时一起删除
                    if (strpos(basename($file), 'thumb_') === 0) {
                        continue;
                    }

                    if (!in_array($file, $usedPaths)) {
                        try {
                            UploadService::deleteFile($file);
                            $result['cleaned']++;
                            $result['details'][] = "删除孤立文件: {$file}";
                        } catch (\Exception $e) {
                            $result['errors']++;
                            $result['details'][] = "删除失败 {$file}: " . $e->getMessage();
                        }
                    }
                }
            }

            return [
                'code' => 0,
                'msg' => '清理完成',
                'data' => $result
            ];

        } catch (\Exception $e) {
            return [
                'code' => 1,
                'msg' => '清理失败：' . $e->getMessage(),
                'data' => null
            ];
        }
    }

    /**
     * 获取文件使用统计
     */
    public static function getFileStats(): array
    {
        try {
            $disk = Filesystem::disk('public');
            $stats = [
                'total_files' => 0,
                'total_size' => 0,
                'avatar_files' => 0,
                'avatar_size' => 0,
                'thumb_files' => 0,
                'thumb_size' => 0
            ];

            // 统计avatars目录
            $avatarDir = 'avatars';
            if ($disk->exists($avatarDir)) {
                $allFiles = $disk->allFiles($avatarDir);
                
                foreach ($allFiles as $file) {
                    $size = $disk->size($file);
                    $stats['total_files']++;
                    $stats['total_size'] += $size;

                    if (strpos(basename($file), 'thumb_') === 0) {
                        $stats['thumb_files']++;
                        $stats['thumb_size'] += $size;
                    } else {
                        $stats['avatar_files']++;
                        $stats['avatar_size'] += $size;
                    }
                }
            }

            // 格式化大小
            $stats['total_size_formatted'] = UploadService::formatFileSize($stats['total_size']);
            $stats['avatar_size_formatted'] = UploadService::formatFileSize($stats['avatar_size']);
            $stats['thumb_size_formatted'] = UploadService::formatFileSize($stats['thumb_size']);

            return [
                'code' => 0,
                'msg' => '统计完成',
                'data' => $stats
            ];

        } catch (\Exception $e) {
            return [
                'code' => 1,
                'msg' => '统计失败：' . $e->getMessage(),
                'data' => null
            ];
        }
    }
} 